package mqtool

import (
	"errors"
	"github.com/nats-io/nats.go"
	"local.public/innerpkg/logger"
	"log"
	"time"
)

var natsClient *nats.Conn

func InitMqConn(natsUrl string) error {
	lnc, err := NewMqConn(natsUrl)
	if err != nil {
		return err
	}
	natsClient = lnc
	logger.Info("建立nats连接过程结束")
	return nil
}

func setupConnOptions() *[]nats.Option {
	opts := make([]nats.Option, 0)
	opts = append(opts, nats.ReconnectWait(2*time.Second))
	opts = append(opts, nats.DisconnectErrHandler(func(nc *nats.Conn, err error) {
		if !nc.IsClosed() {
			logger.Error("Nats连接断开,disconnected!")
		}
	}))
	opts = append(opts, nats.ReconnectHandler(func(nc *nats.Conn) {
		logger.Warn("Nats重新连接，Reconnected [%s]", nc.ConnectedUrl())
	}))
	opts = append(opts, nats.ClosedHandler(func(nc *nats.Conn) {
		if !nc.IsClosed() {
			log.Fatal("Nats exiting: no servers available")
		} else {
			log.Fatal("Nats exiting")
		}
	}))
	return &opts
}

func NewMqConn(natsUrl string) (*nats.Conn, error) {
	opts := setupConnOptions()
	nc, err := nats.Connect(natsUrl, *opts...)
	if err != nil {
		logger.Error("无法链接到NATS服务器:" + err.Error())
		return nil, nil
	}
	logger.Debug("已连接到NATS服务器:", nc.ConnectedUrl())

	return nc, nil
}

func CloseMqConn() {
	if natsClient != nil {
		natsClient.Drain()
		natsClient.Close()
	}
}

func AddNatsSubscribe(subj string, cb nats.MsgHandler) error {
	if _, err := natsClient.Subscribe(subj, cb); err != nil {
		logger.Error(subj+"订购失败", err.Error())
		return err
	}
	logger.Debug(subj + "订购成功\n")
	return nil
}

func MqSend(subj string, payload string) error {
	if natsClient != nil {
		err := natsClient.Publish(subj, []byte(payload))
		return err
	}
	return errors.New("no nats connection")
}
